package com.springboot.config.security;

import com.springboot.enums.ErrorEnum;
import com.springboot.exception.MyException;
import com.sun.el.parser.BooleanNode;
import com.sun.org.apache.xpath.internal.operations.Bool;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 *@descrition:
 *@author lzh
 *@date: 2020/5/23
 */

@ConfigurationProperties(prefix = "jwt")
@Component
@Data
public class JwtConfig {

    //后台私匙
    private String secret;
    //小程序
    private String wxSecret;
    //超时时间
    private long expire;
    //字段名
    private String header;

    /**
     * @descrition:  根据身份ID标识，生成Token
     * @param identityId :
     * @return : java.lang.String
     */
    public String getToken (String identityId, Boolean isWx){
        Date nowDate = new Date();
        //过期时间
        Date expireDate = new Date(nowDate.getTime() + expire * 1000);
        return Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setSubject(identityId)
                .setIssuedAt(nowDate)
                .setExpiration(expireDate)
                .signWith(SignatureAlgorithm.HS512, isWx ? wxSecret : secret)
                .compact();
    }
    /**
     * @descrition:  获取 Token 中注册信息
     * @param token :
     * @return : io.jsonwebtoken.Claims
     */
    public Claims getTokenClaim (String token, Boolean isWx) {
        try {
            return Jwts.parser().setSigningKey(isWx ? wxSecret : secret).parseClaimsJws(token).getBody();
        }catch (Exception e){
            throw new MyException(ErrorEnum.TOKEN_INVALID);
        }
    }
    /**
     * @descrition:  Token 是否过期验证
     * @param expirationTime :
     * @return : boolean
     */
    public boolean isTokenExpired (Date expirationTime) {
        return expirationTime.before(new Date());
    }

}